import React from 'react'
import { createStore,bindActionCreators} from '../redux';

const ADD = 'ADD';
const MINUS = 'MINUS';

function reducer  (state = {number:0}, action) {
    switch (action.type) {
        case ADD:
            return { number: state.number + 1 };
        case MINUS:
            return { number: state.number - 1 };
        default:
            return state;
    }
}
let store = createStore(reducer);


//ActionCreators  action创建者 就是创建action的函数
function add(){
    return {type:ADD}
}
function minus(){
    return {type:MINUS}
}
const actions = { add,minus }


const boundActions = bindActionCreators(actions,store.dispatch)
// 绑定后的
// boundActions= {
//     add(){
//         dispatch(add())
//     },
//     minus(){
//         dispatch(minus())
//     }
// }




export default class Counter1 extends React.Component {
    constructor(props) {
        super(props);
        this.state = { title:'计数器1' ,...store.getState()}
    }
    componentDidMount(){
        this.un = store.subscribe(()=>{
            this.setState(store.getState())
        })
    }
    componentWillUnmount(){
        this.un()
    }
    render(){
        return (
            <div>
                <p>{this.state.number}</p>
                {/* <button onClick={()=>store.dispatch(add())}>+</button>
                <button onClick={()=>store.dispatch(minus())}>-</button> */}
                <button onClick={boundActions.add}>+</button>
                <button onClick={boundActions.minus}>-</button>
            </div>
        )
    }
}
